<template>
  <view class="idea-editor-container">
    <!-- 工具栏 -->
    <view class="toolbar">
      <view class="tool-btn-group">
        <view 
          class="tool-btn"
          :class="{ active: isBold }"
          @click="formatText('bold')"
        >
          <uni-icons type="bold" size="20" :color="isBold ? '#2775b6' : '#666'"></uni-icons>
        </view>
        <view 
          class="tool-btn"
          :class="{ active: isItalic }"
          @click="formatText('italic')"
        >
          <uni-icons type="italic" size="20" :color="isItalic ? '#2775b6' : '#666'"></uni-icons>
        </view>
        <view 
          class="tool-btn"
          @click="formatText('insertUnorderedList')"
        >
          <uni-icons type="list" size="20" color="#666"></uni-icons>
        </view>
      </view>
      
      <view class="tool-btn-group">
        <view 
          class="tool-btn"
          @click="insertImage"
        >
          <uni-icons type="image" size="20" color="#2775b6"></uni-icons>
        </view>
      </view>
    </view>

    <!-- 编辑区域 -->
    <editor
      id="ideaEditor"
      class="editor"
      :placeholder="placeholder"
      @ready="onEditorReady"
      @statuschange="onStatusChange"
      @input="onInput"
    ></editor>

    <!-- 图片预览区 -->
    <view class="image-preview" v-if="images.length > 0">
      <view 
        v-for="(img, index) in images" 
        :key="index"
        class="image-item"
      >
        <image :src="img" mode="aspectFill" class="preview-img"></image>
        <view class="delete-btn" @click="removeImage(index)">
          <uni-icons type="closeempty" size="16" color="#fff"></uni-icons>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue'

const props = defineProps({
  placeholder: {
    type: String,
    default: '写下你的想法...'
  },
  initialContent: {
    type: String,
    default: ''
  },
  initialImages: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['change'])

// 编辑器状态
const editorCtx = ref(null)
const images = ref([...props.initialImages])
const isBold = ref(false)
const isItalic = ref(false)

// 编辑器准备就绪
const onEditorReady = () => {
  uni.createSelectorQuery()
    .select('#ideaEditor')
    .context()
    .exec((res) => {
      editorCtx.value = res[0].context
      // 设置初始内容
      if (props.initialContent) {
        editorCtx.value.setContents({
          html: props.initialContent
        })
      }
    })
}

// 状态变化
const onStatusChange = (e) => {
  const { format } = e.detail
  isBold.value = format.bold || false
  isItalic.value = format.italic || false
}

// 内容输入
const onInput = () => {
  emitContentChange()
}

// 文本格式化
const formatText = (command) => {
  if (!editorCtx.value) return
  editorCtx.value.format(command)
}

// 插入图片
const insertImage = async () => {
  try {
    const res = await uni.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera']
    })
    
    if (res.tempFilePaths.length > 0) {
      const tempPath = res.tempFilePaths[0]
      images.value.push(tempPath)
      
      // 插入到编辑器
      editorCtx.value.insertImage({
        src: tempPath,
        width: '80%',
        success: () => {
          emitContentChange()
        }
      })
    }
  } catch (err) {
    uni.showToast({
      title: '图片添加失败',
      icon: 'none'
    })
  }
}

// 删除图片
const removeImage = (index) => {
  images.value.splice(index, 1)
  emitContentChange()
}

// 触发内容变化事件
const emitContentChange = () => {
  if (!editorCtx.value) return
  
  editorCtx.value.getContents({
    success: (res) => {
      emit('change', {
        content: res.html,
        images: images.value
      })
    }
  })
}

// 暴露方法
defineExpose({
  getContent: () => {
    return new Promise((resolve) => {
      if (!editorCtx.value) {
        resolve({ content: '', images: images.value })
        return
      }
      
      editorCtx.value.getContents({
        success: (res) => {
          resolve({
            content: res.html,
            images: images.value
          })
        },
        fail: () => resolve({ content: '', images: images.value })
      })
    })
  }
})
</script>

<style scoped>
.idea-editor-container {
  border-radius: 12rpx;
  overflow: hidden;
  background-color: #fff;
  box-shadow: 0 2rpx 12rpx rgba(39, 117, 182, 0.1);
  margin-bottom: 30rpx;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16rpx 24rpx;
  border-bottom: 1rpx solid rgba(135, 206, 235, 0.3);
  background-color: #f9fbfe;
}

.tool-btn-group {
  display: flex;
  gap: 20rpx;
}

.tool-btn {
  padding: 8rpx;
  border-radius: 6rpx;
}

.tool-btn.active {
  background-color: rgba(39, 117, 182, 0.1);
}

.editor {
  min-height: 300rpx;
  padding: 24rpx;
  font-size: 28rpx;
  line-height: 1.6;
  color: #333;
}

.image-preview {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
  padding: 16rpx 24rpx;
  border-top: 1rpx solid rgba(135, 206, 235, 0.3);
}

.image-item {
  position: relative;
  width: 120rpx;
  height: 120rpx;
  border-radius: 8rpx;
  overflow: hidden;
}

.preview-img {
  width: 100%;
  height: 100%;
}

.delete-btn {
  position: absolute;
  top: 6rpx;
  right: 6rpx;
  width: 32rpx;
  height: 32rpx;
  background-color: rgba(238, 63, 77, 0.8);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>